package sensimulator.intersection.lanes;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.ImageObserver;
import java.util.HashMap;
import java.util.Observable;

import sennetworkserver.LaneStore;
import sennetworkserver.TrafficLight;
import sensimulator.intersection.Intersection;
import sensimulator.intersection.traffic.Car;
import sensimulator.intersection.traffic.TrafficUser;

public class CarLane extends Lane {

	static final String LIGHT_RED		= "resources/light_red.png";
	static final String LIGHT_ORANGE	= "resources/light_orange.png";
	static final String LIGHT_GREEN		= "resources/light_green.png"; 
	
	private HashMap<Integer, Image> lightImages;
	
	public CarLane(int laneId, Intersection intersection) {
		this(laneId, intersection, true);
	}
	
	public CarLane(int laneId, Intersection intersection, boolean receivesUpdates) {
		super(laneId, intersection, receivesUpdates);
		
		lightImages = new HashMap<Integer, Image>();
		lightImages.put(TrafficLight.RED,		Toolkit.getDefaultToolkit().createImage(LIGHT_RED));
		lightImages.put(TrafficLight.ORANGE,	Toolkit.getDefaultToolkit().createImage(LIGHT_ORANGE));
		lightImages.put(TrafficLight.GREEN,		Toolkit.getDefaultToolkit().createImage(LIGHT_GREEN));
	}

	public void spawnTraffic(boolean triggerSensor) {
		synchronized (traffic) { 
			addTraffic(new Car(this, getFirstNode().getPoint())); 
			
			if (triggerSensor)
				LaneStore.getLane(getId()).getSensor100m().notifyObservers(false);
			
		}
	}

	public void paint(Graphics g, ImageObserver imageObserver) {
		Graphics2D g2 = (Graphics2D) g;
		
		Image lightImage = lightImages.get(LaneStore.getLane(laneId).getTrafficLight().getState());
		
		for (TrafficLightNode light : trafficLights) {
			AffineTransform t = new AffineTransform();
			t.translate(light.getPoint().x, light.getPoint().y);
			t.rotate(-Math.toRadians(light.getRotation()));
			
			g2.setTransform(t);	
			g2.drawImage(lightImage, -lightImage.getWidth(imageObserver) / 2, 
								     -lightImage.getHeight(imageObserver) / 2, imageObserver);
		}
		
		g2.setTransform(new AffineTransform());
	}
}
